package com.kyzh.core.pager.me.user

import android.app.Activity
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.provider.MediaStore
import android.util.Log
import android.view.LayoutInflater
import android.widget.EditText
import android.widget.TextView
import androidx.appcompat.app.AlertDialog
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import com.google.gson.Gson
import com.gushenge.core.base.activity.BaseVmDbActivity
import com.gushenge.core.base.viewmodel.BaseViewModel
import com.gushenge.core.beans.UserInfo
import com.gushenge.core.dao.GlobalKeys
import com.gushenge.core.dao.MMKVConsts
import com.gushenge.core.dao.MMKVConsts.uid
import com.gushenge.core.impls.UserImpl
import com.gushenge.core.listeners.ResultListener
import com.gushenge.core.requests.AppRequest
import com.kyzh.core.R
import com.kyzh.core.utils.*
import com.tencent.imsdk.v2.V2TIMCallback
import com.tencent.qcloud.tuicore.TUILogin
import kotlinx.android.synthetic.main.act_user_data.*
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.cancel
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import org.jetbrains.anko.*
import org.jetbrains.anko.startActivity
import com.gushenge.core.toast
import com.kyzh.core.MyApplication
import com.kyzh.core.pager.weal.address.AddressActivity
import com.kyzh.core.activities.BindPhoneActivity
import com.kyzh.core.pager.home.MainActivity
import com.kyzh.core.databinding.ActUserDataBinding

/**
 * Created by Administrator on 2017/9/14 0014.
 * 我的资料界面
 */

class UserDataActivity : BaseVmDbActivity<BaseViewModel,ActUserDataBinding>(R.layout.act_user_data),ResultListener  {
    private var dialog: AlertDialog?=null
    private var context = this@UserDataActivity
    private var userInfo:UserInfo?=null
    var outputFile:Uri?=null

    private fun initView() {
        mDatabind.logOut.setOnClickListener {
            if(MMKVConsts.imOpen){
                // im退出登录
                TUILogin.logout(object : V2TIMCallback{
                    override fun onSuccess() {
                        uid = ""
                        startActivity(intentFor<MainActivity>().addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP))
                        finish()
                    }
                    override fun onError(p0: Int, p1: String?) {
                        "退出失败，请重试".toast()
                    }
                })
            }else{
                uid = ""
                startActivity(intentFor<MainActivity>().addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP))
                finish()
            }
        }
        /*更换头像*/
        mDatabind.changeHead.setOnClickListener {
            val intent = Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
            intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,"image/*")
            startActivityForResult(intent, 1011)
        }
        /*修改地址*/
        mDatabind.uaddress.setOnClickListener {
            val intent = Intent(this, AddressActivity::class.java)
            intent.putExtra("uid", uid)
            startActivity(intent)
        }
        mDatabind.changeName.setOnClickListener {
            var editText:EditText?=null
            AlertDialog.Builder(this@UserDataActivity, R.style.giftdialog)
                    .setTitle(getString(R.string.pleaseInputWantChangedUserName))
                    .setView(UI {
                        verticalLayout {
                            editText = editText {
                                leftPadding = dip(20)
                                rightPadding = dip(20)
                                backgroundResource = R.drawable.act_search_edittext_bg
                                hint = userInfo?.pet_name
                            }.lparams(matchParent, matchParent){
                                topMargin = dip(20)
                                leftMargin = dip(20)
                                rightMargin  = dip(20)
                            }
                        }
                    }.view)
                    .setNegativeButton(getString(R.string.sure)){_, _ ->
                        val name =editText?.text.toString().trim()
                        if (name.isNotEmpty()){
                            val map = HashMap<String,String>()
                            map[GlobalKeys.PET_NAME] = name
                            val  value = Gson().toJson(map)
                            UserImpl.changeUserInfo(value,this)
                        }else{
                            toast(getString(R.string.nicknameIsEmpty))
                        }
                    }
                    .create()
                    .show()
        }
        mDatabind.genderSelect.setOnClickListener {  showGenderSelect() }
        mDatabind.root.setOnRefreshListener { UserImpl.userInfo(this) }

    }

    private fun showGenderSelect() {
        //要在布局中显示的布局
        val contentView = LayoutInflater.from(this).inflate(R.layout.gender_select_popup, null, false)
        dialog = AlertDialog.Builder(context,R.style.BDAlertDialog).setView(contentView).create()
        dialog?.show()
        val man = contentView.findViewById<TextView>(R.id.gender_man)
        val woman = contentView.findViewById<TextView>(R.id.gender_woman)
        man.setOnClickListener {change("gender","1")}
        woman.setOnClickListener {change("gender","0")}
    }

    override fun onResume() {
        super.onResume()
        if (checkLogin()){
            root.isRefreshing = true
            UserImpl.userInfo(this)
        }else{
            finish()
        }
    }

    private fun setAvataor(uri: Uri) {
        getString(R.string.pleaseWaitToUploadingImage).toast()
        /*post上传*/
        AppRequest.uploadImage(this,uri){
            Log.e("setAvataor: ",this )
            change("face",this)
        }

    }

    private fun change(key:String,value:String){
        val map = HashMap<String,String>()
        map[key] = value
        UserImpl.changeUserInfo(Gson().toJson(map),this)
        dialog?.dismiss()
    }
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        data?.let {
            when(requestCode){
                94->if (resultCode == Activity.RESULT_OK){
                    outputFile?.let {
                        setAvataor(it)
                    }
                    outputFile?:error(getString(R.string.imageCropFailed))
                }
                1011->if (resultCode == Activity.RESULT_OK){
                    it.data?.let {
                        /*outputFile = CropUtils.crop(context,it)*/
                        setAvataor(it)
                    }
                }
            }
        }

    }

    override fun success(bean: Any) {
        when(bean){
            is UserInfo -> {
                userInfo = bean
                Glide.with(MyApplication.instance).load(bean.face).apply(RequestOptions.errorOf(R.drawable.logo_new)).into(head)
                pet_name.text = bean.pet_name
                name.text = bean.user_name
                gender.text = bean.gender
                tvBirthDay.text = bean.birthday
                tvEmail.text = bean.email
                root.isRefreshing = false
                tvEmail.setOnClickListener {
                    if (bean.email.isBlank()){
                        startActivity<BindPhoneActivity>(GlobalKeys.TYPE to GlobalKeys.EMAIL)
                    }
                }
                tvBirthDay.setOnClickListener {
                    if (bean.birthday.isBlank()){
                        startActivity<VerifiedActivity>()
                    }
                }
            }

            is String ->{
                toast(bean)
                GlobalScope.launch {
                    delay(1000)
                    UserImpl.userInfo(context)
                    cancel()
                }
            }
        }
    }

    override fun error(error: String) {
        toast(error)
        root.isRefreshing = false
        dialog?.dismiss()
    }

    override fun initView(savedInstanceState: Bundle?) {
        if (startLogin()){
            initView()
        }else{
            finish()
        }
    }
}